package com.jike.mahjong.service.Imp;


import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jike.mahjong.common.Constants;
import com.jike.mahjong.common.Page;
import com.jike.mahjong.common.util.HttpUtil;
import com.jike.mahjong.common.util.MD5Util;
import com.jike.mahjong.common.util.TransSerialNumTool;
import com.jike.mahjong.dao.PersonDao;
import com.jike.mahjong.dao.PlayerDao;
import com.jike.mahjong.model.*;
import com.jike.mahjong.service.PersonService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by star on 2016/8/23.
 */
@Service("personService")
public class PersonServiceImp implements PersonService {


    @Autowired
    private PersonDao personDao;
    @Autowired
    private PlayerDao playerDao;



    public List<Manager> getAllManager() {


        return personDao.getManagerList();
    }

    public List<Manager> getManagerByConditon(Map<String, Object> paraMap) {


        return personDao.getManagerByConditon(paraMap);
    }

    public List<Manager> getManagerByRole(Map<String, Object> paraMap) {
        return personDao.getManagerByRole(paraMap);
    }

    public Integer changePwd(Map<String, Object> para) {
        return personDao.changePwd(para);
    }

    public Integer addManager(Manager model) {
        model.setPassword(MD5Util.GetMD5Code(Constants.DEFAULT_PWD));
        return personDao.addManager(model);
    }

	@Override
	@Transactional
	public Map<String,Object> insertAgentSellCoin(CoinRecordModel coinRecordModel) throws Exception {
		Map<String,Object> resMap = new HashMap<String, Object>();
		int resultInsert = 0;
		int resultUpdatePerson = 0;
        int resultUpdate = 0;
        Map<String, Object> para = new HashMap<String, Object>();
        para.put("playerId", coinRecordModel.getPlayerId());
        para.put("id", coinRecordModel.getPlayerId());
        para.put("addCoin", coinRecordModel.getMahjongCoin());
        Player model=playerDao.queryPlayerOtherById(para);
        if(model==null){
        	resMap.put("errorCode", "10003");
        	resMap.put("errorMsg", "玩家不存在，请确认");
        	return resMap;
        }
        para.put("userId", coinRecordModel.getManagerId());
        List<Manager> managers = personDao.getManagerByConditon(para);
        Manager manager = managers.get(0);
        if(manager.getAgentCoin()<coinRecordModel.getMahjongCoin()){
        	resMap.put("errorCode", "10002");
        	resMap.put("errorMsg", "余额不足，请您先充值");
			return resMap;
        }
        resultUpdate = this.addCoin(para,model.getId(),coinRecordModel.getMahjongCoin()+"");
        para.put("userId", coinRecordModel.getManagerId());
        resultUpdatePerson = personDao.updateAgentCoin(para);
        if (resultUpdate>0&&resultUpdatePerson>0) {
        	coinRecordModel.setRecordId(TransSerialNumTool.createSerialNum());
            coinRecordModel.setAmount(coinRecordModel.getAmount()*100);
            coinRecordModel.setPlayerRole(Constants.PLAYER_ROLE);
            resultInsert= playerDao.insertRechargeRecord(coinRecordModel);
        }
        if(resultInsert<0){
          throw new Exception();
        }
        resMap.put("playerCoin",model.getDiamond()+coinRecordModel.getMahjongCoin());
        resMap.put("managerCoin",manager.getAgentCoin()-coinRecordModel.getMahjongCoin());
        resMap.put("errorCode", "   0");
    	resMap.put("result", "出售成功");
        return resMap;
	}

//用户加钻石
    public Integer addCoin(Map<String,Object> para,String id,String addCoin) throws Exception {
        List<String> args=new ArrayList<String>();
        RequestModel requestModel=new RequestModel();
        requestModel.setCmd(RequestMethod.addDiamond);
        args.add(id);
        args.add(addCoin);
        requestModel.setArgs(args);

        int resultUpdate = 0;
        // resultUpdate = playerDao.addCoin(para);
        Gson gson=new Gson();
        String paraStr= gson.toJson(requestModel);
        if(Constants.envFlag){
        	String result= HttpUtil.PostWithJson(Constants.BACK_URL,paraStr);
        	JsonParser jsonParser=new JsonParser();
        	JsonObject jsonObject=jsonParser.parse(result).getAsJsonObject();
        	resultUpdate=Integer.parseInt(String.valueOf(jsonObject.get("res")));
        	System.out.println("走接口成功"+resultUpdate);
        }else{
        	resultUpdate=1;
        	System.err.println("未走接口加钻石");
        }
        return resultUpdate;
    }

	@Override
	public List<CoinRecordModel> querySellHistory(Map<String, Object> map) {

        return playerDao.queryRechargeRecord(map);
	}

	@Override
	public Manager queryManagerInfo(Map<String, Object> map) {
		return personDao.getManagerByConditon(map).get(0);
	}

	@Override
	public Page queryAgentList(Map<String, Object> para, Page page) {
        int offset=(page.getCurrentPage()-1)*page.getPageSize();
        para.put("offset",offset);
        para.put("pageSize",page.getPageSize());
        para.put("userTypeDisable", "1");
        List<Manager> managerList=personDao.getManagerByConditon(para);
        int managerCount=personDao.countQueryManagerList(para);
        page.setTotalCount(managerCount);
        page.setData(managerList);
        return page;
	}

	@Override
	@Transactional
	public Integer addAgentCoin(TradeRecord tradeRecord) {
		int resultInsert = 0;
		int resultUpdate = 0;
//        resultInsert= tradeDao.insertTradeRecordByManager(tradeRecord);
        Map<String,Object> para = new HashMap<String,Object>();
        para.put("userId", tradeRecord.getOrderUser());
        para.put("addCoin", tradeRecord.getTradeCoin());
        
        //管理员不走此接口...................
/*        if(Constants.envFlag){
	        List<String> args=new ArrayList<String>();
	        RequestModel requestModel=new RequestModel();
	        requestModel.setCmd(RequestMethod.addDiamond);
	        args.add(tradeRecord.getOrderUser());
	        args.add(tradeRecord.getTradeCoin());
	        requestModel.setArgs(args);
	
	        Gson gson=new Gson();
	        String paraStr= gson.toJson(requestModel);
	        String result= HttpUtil.PostWithJson(Constants.BACK_URL,paraStr);
	        JsonParser jsonParser=new JsonParser();
	        JsonObject jsonObject=jsonParser.parse(result).getAsJsonObject();
	        resultUpdate=Integer.parseInt(String.valueOf(jsonObject.get("res")));
        }
*/
        resultUpdate = personDao.updateAgentCoinByManager(para);
        CoinRecordModel coin=new CoinRecordModel();
        coin.setRecordId(TransSerialNumTool.createSerialNum());
        coin.setMahjongCoin(Integer.valueOf(tradeRecord.getTradeCoin()));
        coin.setPlayerId(tradeRecord.getOrderUser());
        coin.setManagerId(tradeRecord.getManagerId());
        coin.setAmount(0);
        coin.setPlayerRole(Constants.MANAGER_ROLE);
        resultInsert= playerDao.insertRechargeRecord(coin);
        if(resultInsert<0||resultUpdate<0){
          try {
        	  throw new Exception();
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
        return resultInsert;
	}

	@Override
	public Integer agentChangePwd(Map<String, Object> para) {
		return personDao.changePwd(para);
	}

    @Override
    public Integer deleteManager(Map<String, Object> para) {
        return personDao.deleteManager(para);
    }

}
